<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 登录卡片 -->
      <div class="login-block">
        <div class="login-card">
          <!-- 右侧登录表单区域 -->
          <div class="login-right">
            <div class="login-form">
              <h2 class="login-title">系统登录</h2>

              <el-form
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
                class="form-container"
                size="large"
              >
                <!-- 账号输入 -->
                <el-form-item prop="account">
                  <el-input
                    v-model="loginForm.account"
                    placeholder="请输入账号"
                    clearable
                  >
                    <template #prefix>
                      <img src="~/assets/login/icon_user_nor.svg" alt="" />
                    </template>
                  </el-input>
                </el-form-item>

                <!-- 密码输入 -->
                <el-form-item prop="password">
                  <el-input
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请输入密码"
                    show-password
                    clearable
                  >
                    <template #prefix>
                      <img src="~/assets/login/icon_mima_nor.svg" alt="" />
                    </template>
                  </el-input>
                </el-form-item>

                <!-- 验证码输入 -->
                <!-- <el-form-item prop="verificationCode" style="display: block">
                  <el-input
                    v-model="loginForm.verificationCode"
                    placeholder="请输入验证码"
                    clearable
                  >
                    <template #suffix>
                      <span
                        class="send-code-text"
                        :class="{ disabled: isCodeSending || countdown > 0 }"
                        @click="sendVerificationCode"
                      >
                        {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
                      </span>
                    </template>
                  </el-input>
                </el-form-item> -->
                <el-form-item label="">
                  <div class="row" style="display: flex; align-items: center;justify-content: space-between;">
                    <el-input
                      v-model="loginForm.verificationCode"
                      placeholder="图片验证码"
                      style="width: 268px"
                      @keyup.enter="handleLogin"
                    />

                    <Image
                      v-if="captcha"
                      v-loading="captchaLoading"
                      :src="captcha"
                      class="captcha"
                      @click="getCaptchaApi"
                      style="margin-left: 10px;"
                    />
                  </div>
                </el-form-item>
                <!-- 记住密码 -->
                <el-form-item class="remember-password">
                  <el-checkbox v-model="loginForm.rememberPassword">
                    记住密码
                  </el-checkbox>
                </el-form-item>

                <!-- 登录按钮 -->
                <el-form-item>
                  <el-button
                    type="primary"
                    class="login-btn"
                    :loading="isLoading"
                    @click="handleLogin"
                    size="large"
                  >
                    登录
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { ref, reactive, watch, onMounted } from 'vue';
import { loginAccount, getCaptcha } from '~/api/account';
import { MD5 } from 'crypto-js';
// //console.log()
// 登录表单接口
interface LoginForm {
  account: string;
  password: string;
  verificationCode: string;
  rememberPassword: boolean;
}
// // 避免自动填充
const captcha = ref('');
const captchaLoading = ref(false);
// 响应式数据
const loginFormRef = ref<FormInstance>();
const isLoading = ref(false);
const isCodeSending = ref(false);
const countdown = ref(0);
const uuid = ref('');
// 登录表单数据
const loginForm = reactive<LoginForm>({
  account: '',
  password: '',
  verificationCode: '',
  rememberPassword: false,
});

// 本地存储键名常量
const LS_ACCOUNT_KEY = 'clinic_login_account';
const LS_PASSWORD_KEY = 'clinic_login_password';

// 安全提示：此处直接存明文密码（或简单 Base64）存在风险，生产可改为：
// 1. 仅存账号 + 后端发的 refresh token；
// 2. 或使用 Web Crypto 加密后再存。
// 这里按需求实现最简单持久化。

// 读取本地已记住的账号/密码
onMounted(() => {
  try {
    const savedAccount = localStorage.getItem(LS_ACCOUNT_KEY);
    const savedPwd = localStorage.getItem(LS_PASSWORD_KEY);
    if (savedAccount && savedPwd) {
      loginForm.account = savedAccount;
      // 这里存的是明文；如果以后改成 Base64，可在此解码 atob(savedPwd)
      loginForm.password = savedPwd;
      loginForm.rememberPassword = true;
    }
  } catch (e) {
    //console.warn('读取本地登录信息失败', e);
  }
  getCaptchaApi();
});

// 监听取消勾选时清除本地存储
watch(
  () => loginForm.rememberPassword,
  (val) => {
    if (!val) {
      try {
        localStorage.removeItem(LS_ACCOUNT_KEY);
        localStorage.removeItem(LS_PASSWORD_KEY);
      } catch (e) {
        //console.warn('清除本地登录信息失败', e);
      }
    }
  }
);

// 表单验证规则
const loginRules: FormRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
};
// 获取验证码
const getCaptchaApi = async () => {
  try {
    if (captchaLoading.value) {
      return;
    }

    captchaLoading.value = true;

    const result = await getCaptcha();

    if (result.code == 200) {
      captcha.value = result.data.img;
      uuid.value = result.data.uuid;
    }
  } catch (error) {
    //console.log(error);
  } finally {
    captchaLoading.value = false;
  }
};
// 发送验证码
const sendVerificationCode = async (): Promise<void> => {
  if (!loginForm.account) {
    ElMessage({
      type: 'warning',
      message: '请先输入账号',
        duration: 2000,

    });
    return;
  }

  try {
    isCodeSending.value = true;
    // 这里调用发送验证码的 API
    // await $fetch('/api/auth/send-code', {
    //   method: 'POST',
    //   body: { account: loginForm.account }
    // })

    // ElMessage({
    //   type: 'success',
    //   message: '验证码已发送',
    // });
    startCountdown();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '验证码发送失败',
        duration: 2000,

    });
  } finally {
    isCodeSending.value = false;
  }
};

// 倒计时
const startCountdown = (): void => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};
// 注意：获取验证码调用已移至 onMounted 中的合并逻辑
// 登录处理（移除 try/catch，按接口 code 判断成败）
const handleLogin = async (): Promise<void> => {
  if (!loginFormRef.value) return;

  const valid = await loginFormRef.value
    .validate()
    .then(() => true)
    .catch(() => false);
  if (!valid) return;

  isLoading.value = true;
  const result = await loginAccount({
    phone: loginForm.account,
    password: MD5(loginForm.password).toString(),
    code: loginForm.verificationCode,
    uuid: uuid.value,
  });

  if (result?.code != '200') {
    // ElMessage({
    //   type: 'error',
    //   message: result?.msg || result?.msg || '登录失败，请检查账号密码',
    //     duration: 2000,

    // });
    isLoading.value = false;
    getCaptchaApi();
    return;
  }

  // 登录成功
  setUserInfo(result.data);
  setToken(result.data.token);

  // 记住密码逻辑：成功后再写入，避免失败存脏数据
  if (loginForm.rememberPassword) {
    try {
      localStorage.setItem(LS_ACCOUNT_KEY, loginForm.account);
      // 如需简单混淆可用 btoa(loginForm.password)
      localStorage.setItem(LS_PASSWORD_KEY, loginForm.password);
    } catch (e) {
      //console.warn('写入本地登录信息失败', e);
    }
  } else {
    try {
      localStorage.removeItem(LS_ACCOUNT_KEY);
      localStorage.removeItem(LS_PASSWORD_KEY);
    } catch (e) {
      //console.warn('清除本地登录信息失败', e);
    }
  }

  ElMessage({
    type: 'success',
    duration: 2000,
    message: '登录成功',

  });
  isLoading.value = false;
  navigateTo('/dashboard');
};

// 页面元数据
definePageMeta({
  layout: 'auth',
  title: '系统登录',
});
</script>
<style lang="scss">
.login-page {
  .el-checkbox__inner {
    border-radius: 50% !important;
  }
  .el-input__inner {
    padding: 15px 3px !important;
  }
}
</style>
<style scoped lang="scss">
.send-code-text {
  color: #16ada4;
  cursor: pointer;
}
.login-page {
  width: 100%;
  height: 100%;
  background-color: white;
}

.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  background-image: url('@/assets/login/bg_home_nor_compressed.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
}

.login-block {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 861px;
  height: 528px;
  background-image: url('@/assets/images/block.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-card {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 829px;
  height: 496px;
  background: linear-gradient(
    342deg,
    #feffff 0%,
    rgba(251, 255, 254, 0.4) 88%,
    #ffffff 100%
  );
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.12);
  border-radius: 24px 24px 24px 24px;
}

.login-right {
  width: 510px;
  height: 496px;
  background: #ffffff;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.12);
  border-radius: 24px 24px 24px 24px;
}

.login-form {
  width: 100%;
  padding: 0px 55px;
}

.login-title {
  padding-top: 50px;
  padding-bottom: 50px;
  font-size: 26px;
  color: rgba(0, 0, 0, 0.9);
  line-height: 44px;
  letter-spacing: 1px;
  text-align: center;
}

.form-container {
  .el-form-item {
    margin-bottom: 25px;

    :deep(.el-input__inner) {
      padding: 15px 20px;
      font-size: 16px;
    }
  }
}

.verification-container {
  .el-input {
    width: 100%;
  }
}

.verification-form-item {
  margin-bottom: 16px !important;
}

.login-btn {
  width: 400px;
  height: 40px;
  background: #16ada4;
  border-radius: 6px 6px 6px 6px;

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.remember-password {
  margin-bottom: 0px;

  :deep(.el-form-item__content) {
    line-height: 1 !important;

    .el-checkbox {
      height: auto;
    }
  }
}

:deep(.el-checkbox) {
  .el-checkbox__label {
    color: rgba(0, 0, 0, 0.9);
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-card {
    flex-direction: column;
    width: 95vw;
    max-width: 400px;
  }

  .login-right {
    padding: 30px 25px;
  }

  .login-title {
    font-size: 24px;
  }
}
</style>
